#include "EngineEntity.h"

EngineEntity::EngineEntity()
{
	components = new IEngineComponentCollection();
}

EngineEntity::~EngineEntity(void)
{
	components->clear();
}

void EngineEntity::addComponent(EnginePointer<IEngineComponent> component)
{
	components->push_back(component);
}

list<EnginePointer<IEngineComponent>>::iterator EngineEntity::ComponentsBegin()
{
	return components->begin();
}

list<EnginePointer<IEngineComponent>>::iterator EngineEntity::ComponentsEnd()
{
	return components->end();
}

void EngineEntity::Serialize(EnginePointer<ISerializerWriteContext>& context, char* name)
{
	context->StartItem(name, "EngineEntity", "1.0");
	context->StartItem("Components");
	for (list<EnginePointer<IEngineComponent>>::iterator it = components->begin(); it != components->end(); it++)
	{
		(*it)->Serialize(context, "Component");
	}
	context->EndItem("Components");
	context->EndItem(name);
}

EngineEntity* EngineEntity::Deserialize(EnginePointer<ISerializerReadContext>& context)
{
	EngineEntity* entity = new EngineEntity();
	int index = 0;
	char* childName = context->ChildName(index);

	while (childName != NULL)
	{
		if (strcmp(childName, "Components") == 0)
		{
			int componentIndex = 0;
			context->MoveToChild(index);
			childName = context->ChildName(componentIndex);

			while (childName != NULL)
			{
				if (strcmp(childName, "Component") == 0)
				{
					context->MoveToChild(componentIndex);
					entity->addComponent(IEngineComponent::Deserialize(context));
					context->MoveToParent();
				}
				childName = context->ChildName(++componentIndex);
			}
			context->MoveToParent();
		}
		childName = context->ChildName(++index);
	}
	
	return entity;
}